<?php

namespace V1;
class OrderList extends \ResourceClass
{
    public $isActive = true;
    public $remark = '订单下载';
    public $orderStatus; // 提货单状态
    public $directOrderStatus; // 直购单状态
    public $tradeStatus; // 提货单
    public $directTradeStatus; // 直购单
    public $orderInfo;
    public $orderGoods;

    public function __construct()
    {

        // 提货单状态
        $this->orderStatus = array(
            'JH_01' => 10, //等待买家付款
            'JH_02' => \Orm\PickUp\PickUpClass::STATUS_CHECKED, //等待卖家发货
            'JH_03' => \Orm\PickUp\PickUpClass::STATUS_ALREADY, //等待买家确认收货
            'JH_04' => \Orm\PickUp\PickUpClass::STATUS_ALREADY, //交易成功
            'JH_05' => array(\Orm\PickUp\PickUpClass::STATUS_REFUSE, \Orm\PickUp\PickUpClass::STATUS_CANCEL), //交易关闭
            'JH_99' => 0 //所有订单
        );

        // 直购单状态
        $this->directOrderStatus = array(
            'JH_01' => \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_NEW, //等待买家付款
            'JH_02' => \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_DELIVERY,//等待卖家发货
            'JH_03' => \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_FINISH, //等待买家确认收货
            'JH_04' => \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_FINISH, //交易成功
            'JH_05' =>  \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_DEFAULT, //交易关闭
            'JH_99' => 0 //所有订单
        );

        $this->tradeStatus = array(
            \Orm\PickUp\PickUpClass::STATUS_REFUSE => 'JH_05', //交易关闭
            \Orm\PickUp\PickUpClass::STATUS_CANCEL => 'JH_05', //交易关闭
            \Orm\PickUp\PickUpClass::STATUS_CHECKED => 'JH_02', //等待卖家发货
            \Orm\PickUp\PickUpClass::STATUS_ALREADY => 'JH_03', //等待买家确认收货
            \Orm\PickUp\PickUpClass::STATUS_FINISH => 'JH_04' //交易成功
        );

        $this->directTradeStatus = array(
            \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_DEFAULT=> 'JH_05', //交易关闭
            \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_DELIVERY => 'JH_02', //等待卖家发货
            \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_FINISH => 'JH_03', //等待买家确认收货
            \Orm\ShopOrder\ShopOrderClass::ORDER_STATUS_NEW => 'JH_01' //等待买家付款
        );

        $this->orderInfo = array('PlatOrderNo' => '',              //订单号
            'tradeStatus' => '',              //订单交易状态【等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05】
            'tradeStatusdescription' => '',   //订单交易说明
            'tradetime' => '',                //交易时间【格式:yyyy-MM-dd HH:mm:ss】
            'payorderno' => '',               //支付单号
            'country' => 'CN',                  //国家名称【CN】
            'province' => '',                 //州/省
            'city' => '',                     //城市
            'area' => '',                     //区县
            'town' => '',                     //镇/街道
            'address' => '',                  //地址
            'zip' => '',                      //邮编
            'phone' => '',                    //电话
            'mobile' => '',                   //手机
            'email' => '',                    //Email
            'customerremark' => '',           //买家备注
            'sellerremark' => '[beaba新零售]',             //卖家备注
            'postfee' => '',                  //邮资
            'goodsfee' => '',                 //货款金额
            'totalmoney' => '',               //合计应收
            'favourablemoney' => '',          //订单总优惠金额
            'commissionvalue' => '',          //佣金
            'taxamount' => '',                //订单税费总额
            'tariffamount' => '',             //订单关税金额
            'addedvalueamount' => '',         //订单增值税金额
            'consumptiondutyamount' => '',    //订单消费税金额
            'sendstyle' => '',                //货运方式
            'qq' => '',                       //QQ
            'paytime' => '',                  //支付时间【格式:yyyy-MM-dd HH:mm:ss】
            'invoicetitle' => '',             //发票抬头
            'taxpayerident' => '',            //纳税人识别号
            'codservicefee' => '',            //COD服务费
            'cardtype' => 'JH_01',                 //证件类型【身份证=JH_01，护照=JH_02，港澳通行证=JH_03】
            'idcard' => '',                   //证件号码
            'idcardtruename' => '',           //证件真实姓名
            'receivername' => '',             //收货人真实姓名
            'nick' => '',                     //买家昵称
            'whsecode' => '',                 //商品所在仓库编号
            'IsHwgFlag' => 0,                //是否为海外购【是=1；否=0】
            'ShouldPayType' => '',            //结算方式【担保交易；银行收款；现金收款；货到付款；欠款记应收；客户预付款；多种结算】
            'goodinfos' => ''                 //商品集合
        );
        $this->orderGoods = array('ProductId' => '',                //商品ID或SKUID
            'suborderno' => '',               //子订单号
            'tradegoodsno' => '',             //SKU编码
            'tradegoodsname' => '',           //商品名称
            'tradegoodsspec' => '',           //商品规格
            'goodscount' => '',               //商品数量
            'price' => '',                    //单价
            'discountmoney' => '',            //订单优惠金额
            'taxamount' => '',                //商品税费
            'refundStatus' => '',             //退款状态
            'Status' => '',                   //订单交易状态
            'remark' => ''                    //货品备注
        );
    }

    /*
     * 获取订单列表
     */
    public function post(array $post)
    {
        $data = array();
        $orderSn = isset($post['PlatOrderNo']) ? $post['PlatOrderNo'] : '';
        if(!$orderSn) {
            if (!isset($post['OrderStatus'])) {
                printError('缺少参数：OrderStatus', "40001");
            } else {
                if (!isset($this->orderStatus[$post['OrderStatus']])) {
                    printError('参数错误：OrderStatus', "40002");
                }
            }
            if (!isset($post['StartTime'])) {
                printError('缺少参数：StartTime', "40001");
            } else {
                if ($this->checkDateTimeFormat($post['StartTime']) != true) {
                    printError('StartTime参数格式错误', "40002");
                }
            }
            if (!isset($post['EndTime'])) {
                printError('缺少参数：EndTime', "40001");
            } else {
                if ($this->checkDateTimeFormat($post['EndTime']) != true) {
                    printError('EndTime参数格式错误', "40002");
                }
            }
            if (!isset($post['PageIndex']) || (int)$post['PageIndex'] < 1) {
                printError('缺少参数：PageIndex，或者该参数错误', "40001");
            } else {
                if ((int)$post['PageIndex'] < 1) {
                    printError('PageIndex参数错误', "40002");
                }
            }
            if (!isset($post['PageSize'])) {
                printError('缺少参数：PageSize', "40001");
            } else {
                if ((int)$post['PageSize'] < 1) {
                    printError('PageSize参数错误', "40002");
                }
            }
        }
        $OrderStatus = $post['OrderStatus'];
        $where = array();

        $where[] = 'status > 0';
        if ($orderSn) {
            $where[] = 'number = "' . $orderSn . '"';
        } else {
            $order_where = array();
            // 提货单状态
            if (isset($this->orderStatus[$OrderStatus])) {
                if(is_array($this->orderStatus[$OrderStatus])) {
                    if ($this->orderStatus[$OrderStatus]) {
                        $order_where[] = 'status in(' . implode(',', $this->orderStatus[$OrderStatus]) . ') and type=1';
                    }else{
                        $order_where[] = 'status = 10 and type=1';//不存在的状态
                    }
                } else {
                    if ($this->orderStatus[$OrderStatus]) {
                        $order_where[] = 'status = "' . $this->orderStatus[$OrderStatus] . '" and type=1';
                    }
                }
            }else{
                $order_where[] = 'status = 10 and type=1';//不存在的状态
            }


            // 直购单状态
            $direct_where = array();
            if (isset($this->directOrderStatus[$OrderStatus])) {
                if(is_array($this->directOrderStatus[$OrderStatus])) {
                    if ($this->directOrderStatus[$OrderStatus]) {
                        $direct_where[] = 'status in(' . implode(',', $this->directOrderStatus[$OrderStatus]) . ') and type=2';
                    }else{
                        $direct_where[] = 'status = 10 and type=2';//不存在的状态
                    }
                } else {
                    if ($this->directOrderStatus[$OrderStatus]) {
                        $direct_where[] = 'status = "' . $this->directOrderStatus[$OrderStatus] . '" and type=2';
                    }
                }
            }else{
                $direct_where[] = 'status = 10 and type=2';//不存在的状态
            }

            $where[] = '((' .implode(' AND ',$order_where).') or ('.implode(' AND ',$direct_where).'))';

            if ($post['StartTime']) {
                $where[] = 'insert_time >= "' . $post['StartTime'] . '"';
            }
            if ($post['EndTime']) {
                $where[] = 'insert_time <= "' . $post['EndTime'] . '"';
            }
        }

        $where = implode(' AND ', $where);
        $OrderBiz = new \Biz\Order();
        $shop_list_result = $OrderBiz->getOrderList($where, (($post['PageIndex']-1)*$post['PageSize']), $post['PageSize'], 'insert_time ASC');
        $orders = array();
        if (isset($shop_list_result['lists']) && $shop_list_result['lists']) {
            foreach ($shop_list_result['lists'] as $item) {
                //客户名称
                try {
                    $customerBiz = new \Biz\Customer();
                    $customerInfo = $customerBiz->getById($item['customer_id']);
                    if (!$customerInfo['name']) {
                        $customerInfo['name'] = '无';
                    }
                }catch (\Exception $e){
                    $customerInfo['name'] = '无';
                }

                $tmp = $this->orderInfo;
                $tmp['PlatOrderNo'] = $item['number'];
                $tmp['nick'] = $customerInfo['name'];
                $tmp['receivername'] = $item['ship_name'];
                $tmp['mobile'] = $item['ship_mobile'];

                if($item['type'] == 1){
                    $tmp['tradeStatus'] = isset($this->tradeStatus[$item['status']]) ? $this->tradeStatus[$item['status']] : 'JH_99';
                } else {
                    $tmp['tradeStatus'] = isset($this->directTradeStatus[$item['status']]) ? $this->directTradeStatus[$item['status']] : 'JH_99';
                }
                $tmp['goodsfee'] = $item['amount'];
                $tmp['totalmoney'] = $item['real_amount'];
                $tmp['customerremark'] = $item['remark'];
                $tmp['tradetime'] = $item['insert_time'];
                $tmp['province'] = isset($item['province_name']) ? $item['province_name'] : '';
                $tmp['city'] = isset($item['city_name']) ? $item['city_name'] : '';
                $tmp['area'] = isset($item['area_name']) ? $item['area_name'] : '';
                $tmp['address'] = $tmp['province'].$tmp['city'].$tmp['area'].$item['address'];

                if ($item['type'] == 1) {
                    $PickUpDetailBiz = new \Biz\PickUpDetail\PickUpDetail();
                    $order_detail = $PickUpDetailBiz->getPickUpDetailByPid($item['id']);
                    $orderDetail = array();
                    if (isset($order_detail['lists']) && $order_detail['lists']) {
                        foreach ($order_detail['lists'] as $val) {
                            try {
                                $productOrm = new \Orm\ProductSku\ProductSkuClass();
                                $productOrm->loadById($val['product_sku_id']);
                            } catch (\Exception $e) {
                            }
                            $tmp_detail = $this->orderGoods;
                            $tmp_detail['ProductId'] = $val['product_sku_id'];
                            $tmp_detail['suborderno'] = $item['number'].'-'.$val['product_sku_id'];
                            $tmp_detail['tradegoodsno'] = $productOrm['sku_code'];//$val['product_number'];
                            $tmp_detail['tradegoodsname'] = $val['product_name'];
                            $tmp_detail['tradegoodsspec'] = $this->unAttr($val['product_attr']);
                            $tmp_detail['goodscount'] = $val['real_send_num'];
                            $tmp_detail['price'] = $val['unit_price'];
                            $tmp_detail['discountmoney'] = 0;
                            $tmp_detail['taxamount'] = 0;
                            $tmp_detail['refundStatus'] = 'JH_07';//没有退款
                            $tmp_detail['Status'] = 'JH_02';//其他
                            $tmp_detail['remark'] = $val['standard_string'];
                            $orderDetail[] = $tmp_detail;
                        }
                    }
                    $tmp['goodinfos'] = $orderDetail;
                    $orders[] = $tmp;
                } elseif ($item['type'] == 2) {
                    $shopDetail = new \Biz\Shop\Detail();
                    $shopDetailList = $shopDetail::getShopDetailByShopId($item['id']);
                    $orderDetail = array();

                    if (isset($shopDetailList['lists']) && $shopDetailList['lists']) {
                        foreach ($shopDetailList['lists'] as $val) {
                            $tmp_detail = $this->orderGoods;
                            $tmp_detail['ProductId'] = $val['product_sku_id'];
                            $tmp_detail['suborderno'] = $item['number'].'-'.$val['product_sku_id'];
                            $tmp_detail['tradegoodsno'] = $val['product_number'];//$val['product_number'];
                            $tmp_detail['tradegoodsname'] = $val['product_name'];
                            $tmp_detail['tradegoodsspec'] = $this->unAttr($val['product_attr']);
                            $tmp_detail['goodscount'] = $val['num'];
                            $tmp_detail['price'] = $val['rank_price'];
                            $tmp_detail['discountmoney'] = 0;
                            $tmp_detail['taxamount'] = 0;
                            $tmp_detail['refundStatus'] = 'JH_07';//没有退款
                            $tmp_detail['Status'] = 'JH_02';//其他
                            $tmp_detail['remark'] = $val['standard_string'];
                            $orderDetail[] = $tmp_detail;
                        }
                    }
                    $tmp['goodinfos'] = $orderDetail;
                    $orders[] = $tmp;
                }


            }
        }
        $data['code'] = '10000';
        $data['message'] = 'SUCCESS';
        $data['numtotalorder'] = isset($shop_list_result['total']) ? $shop_list_result['total'] : 0;
        $data['orders'] = $orders;
        return $data;
    }

    private function unAttr($str){
        $return_str = '';
        $strArr = @unserialize($str);
        if(is_array($strArr) && count($strArr)>0){
            foreach ($strArr as $key => $val){
                $return_str .= $key.':'.$val.';';
            }
        }
        return $return_str;
    }

}